package com.ruoyi.business.base;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.CaseFormat;
import com.ruoyi.common.utils.StringUtils;

import java.lang.reflect.Field;
import java.util.StringJoiner;

/**
 * Jo LambdaQueryWrapper 查询对象
 *
 * @author Jyl
 */
public class JoLambdaQW<T> extends QueryWrapper<T>
{

    private JoSqlUtil joSqlUtil = new JoSqlUtil();

    /**
     * 构建列名
     *
     * @param entityClass
     * @return
     */
    public JoLambdaQW buildColumn(Class<?> entityClass)
    {
        StringJoiner joiner = new StringJoiner(" , ");
        Field[] fields = entityClass.getDeclaredFields();
        for (Field fi : fields)
        {
            fi.setAccessible(true);

            //跳过数据库非处理字段
            if (fi.isAnnotationPresent(TableField.class)
                && !fi.getAnnotation(TableField.class).exist())
            {
                continue;
            }
            // 检查是否存在@Id注解
            if (fi.isAnnotationPresent(TableField.class)
                && StringUtils.isNotEmpty(fi.getAnnotation(TableField.class).value()))
            {
                TableField idAnnotation = fi.getAnnotation(TableField.class);
                joiner.add(idAnnotation.value());
            } else
            {
                String resultStr = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fi.getName());
                joiner.add(resultStr);
            }
        }
        if (StringUtils.isNotEmpty(this.getSqlSelect())) joiner.add(this.getSqlSelect());
        this.select(joiner.toString());

        if (entityClass.getSuperclass() == null) return this;
        return buildColumn(entityClass.getSuperclass());
    }

    /**
     * 主键集对象装换语句
     *
     * @param sourceTableName 数据源表名称
     * @param sourceName      数据源映射字段
     * @param convertIds      转换主键集
     * @param convertAs       转换接收别名
     * @return
     */
    public JoLambdaQW reflection(String sourceTableName, String sourceName, String convertIds, String convertAs)
    {
        String sql = joSqlUtil.sqlSelect(sourceTableName, convertIds, sourceName);
        this.reflection(sql, convertAs);
        return this;
    }

    /**
     * 字典 映射转换
     *
     * @param dictType   字典类型
     * @param convertIds 转换主键集
     * @param convertAs  转换接收别名
     * @return
     */
    public JoLambdaQW reflectionDict(String dictType, String convertIds, String convertAs)
    {
        String sql = joSqlUtil.sqlDictSelect(convertIds, dictType);
        this.reflection(sql, convertAs);
        return this;
    }

    public JoLambdaQW reflection(String child, String as)
    {
        String ref = "(" + child + ") as " + as;
        String sql = this.getSqlSelect().replaceAll(as, ref);
        this.select(sql);
        return this;
    }

}
